{
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5-final"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python_defaultSpec_1598518399830",
   "display_name": "Python 3.8.5 64-bit"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2,
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "给定一个机票的字符串二维数组 [from, to]，子数组中的两个成员分别表示飞机出发和降落的机场地点，对该行程进行重新规划排序。所有这些机票都属于一个从 JFK（肯尼迪国际机场）出发的先生，所以该行程必须从 JFK 开始。\n",
    "\n",
    "说明:\n",
    "\n",
    "如果存在多种有效的行程，你可以按字符自然排序返回最小的行程组合。例如，行程 [\"JFK\", \"LGA\"] 与 [\"JFK\", \"LGB\"] 相比就更小，排序更靠前\n",
    "所有的机场都用三个大写字母表示（机场代码）。\n",
    "假定所有机票至少存在一种合理的行程。\n",
    "示例 1:\n",
    "```\n",
    "输入: [[\"MUC\", \"LHR\"], [\"JFK\", \"MUC\"], [\"SFO\", \"SJC\"], [\"LHR\", \"SFO\"]]\n",
    "输出: [\"JFK\", \"MUC\", \"LHR\", \"SFO\", \"SJC\"]\n",
    "```\n",
    "示例 2:\n",
    "```\n",
    "输入: [[\"JFK\",\"SFO\"],[\"JFK\",\"ATL\"],[\"SFO\",\"ATL\"],[\"ATL\",\"JFK\"],[\"ATL\",\"SFO\"]]\n",
    "输出: [\"JFK\",\"ATL\",\"JFK\",\"SFO\",\"ATL\",\"SFO\"]\n",
    "解释: 另一种有效的行程是 [\"JFK\",\"SFO\",\"ATL\",\"JFK\",\"ATL\",\"SFO\"]。但是它自然排序更大更靠后。\n",
    "```\n",
    "来源：力扣（LeetCode）\n",
    "链接：https://leetcode-cn.com/problems/reconstruct-itinerary\n",
    "著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "思路：_\n",
    "\n",
    "先转换成字典查找，用空间换时间\n",
    "\n",
    "\n",
    "\n",
    "没考虑的点：\n",
    "\n",
    "如果有多个结果，需要排序选一个，但是如果只选第一个，可能不能把所有的票都安排完。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution:\n",
    "    def findItinerary(self, tickets: List[List[str]]) -> List[str]:\n",
    "        dic = {}\n",
    "        for ticket in tickets:\n",
    "            if ticket[0] in dic:\n",
    "                bisect.insort_left(dic[ticket[0]], ticket[1])\n",
    "            else:\n",
    "                dic[ticket[0]] = [ticket[1]]\n",
    "\n",
    "        res = [\"JFK\"]\n",
    "        while dic:\n",
    "            if res[-1] not in dic:\n",
    "                break\n",
    "            tmp_list = dic[res[-1]]\n",
    "            end = tmp_list[0]\n",
    "            tmp_list.remove(end)\n",
    "            if not tmp_list:\n",
    "                del dic[res[-1]]\n",
    "            res.append(end)\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import heapq\n",
    "import collections"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution:\n",
    "    def findItinerary(self, tickets: List[List[str]]) -> List[str]:\n",
    "        def dfs(curr: str):\n",
    "            while vec[curr]:\n",
    "                tmp = heapq.heappop(vec[curr])\n",
    "                dfs(tmp)\n",
    "            stack.append(curr)\n",
    "\n",
    "        vec = collections.defaultdict(list)\n",
    "        for depart, arrive in tickets:\n",
    "            vec[depart].append(arrive)\n",
    "        for key in vec:\n",
    "            heapq.heapify(vec[key])\n",
    "        \n",
    "        stack = list()\n",
    "        dfs(\"JFK\")\n",
    "        return stack[::-1]\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "['JFK', 'NRT', 'JFK', 'KUL']"
     },
     "metadata": {},
     "execution_count": 32
    }
   ],
   "source": [
    "Solution().findItinerary([[\"JFK\",\"KUL\"],[\"JFK\",\"NRT\"],[\"NRT\",\"JFK\"]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ]
}